#include "recboxitem.h"
#include "ui_recboxitem.h"
#include<QDebug>
#include<QPropertyAnimation>
#include<QJsonParseError>
#include<QJsonArray>
#include<musiclist.h>
#include<QJsonObject>
#include<QUuid>

QMap<QString,QPixmap> g_cover_cache;//全局图像缓存


RecBoxItem::RecBoxItem(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBoxItem)
{
    ui->setupUi(this);
    ui->musicImageBox->installEventFilter(this);
    if(!manager){
        manager = new QNetworkAccessManager(this);
    }


}

RecBoxItem::~RecBoxItem()
{
    delete ui;
}



void RecBoxItem::setRecText(const QString &text)
{
    ui->recBoxItem->setText(text);
}

void RecBoxItem::setRecImage(const QString &imageUrl)
{

    //先看内存中有没有缓存
    if(g_cover_cache.contains(imageUrl)){
        qDebug()<<"从内存缓存加载图片"<<imageUrl;
        ui->recMusicImage->setPixmap(g_cover_cache[imageUrl].scaled(
                                         ui->recMusicImage->size(),
                                         Qt::KeepAspectRatio,
                                         Qt::SmoothTransformation
                                         ));
        return;

    }

    QString localPath=cacheFilePath(imageUrl);

    if(QFile::exists(localPath)){
        QPixmap pix(localPath);
        if(!pix.isNull()){
            qDebug()<<"从磁盘中加载图片"<<localPath;

            ui->recMusicImage->setPixmap(
                            pix.scaled(
                                ui->recMusicImage->size(),
                                Qt::KeepAspectRatio,
                                Qt::SmoothTransformation));

           return;
        }

    }

    //没有缓存，网络加载


    // 发起 GET 请求
        QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(imageUrl)));

        // 异步回调
        connect(reply, &QNetworkReply::finished, this, [=]() {
            if (reply->error() == QNetworkReply::NoError)
            {
                QByteArray imgData = reply->readAll();
                QPixmap pix;

                if (pix.loadFromData(imgData)) {
                    // 缩放到 QLabel 大小

                    if(!pix.save(localPath,"JPG",85)){
                        qDebug()<<"保持磁盘失败";
                    }

                    g_cover_cache.insert(imageUrl, pix);

                    ui->recMusicImage->setPixmap(
                        pix.scaled(ui->recMusicImage->size(),
                                   Qt::KeepAspectRatio,
                                   Qt::SmoothTransformation));
                } else {
                    qDebug() << "图片数据加载失败";
                }
            }
            else
            {
                qDebug() << "图片请求失败:" << reply->errorString();
            }

            reply->deleteLater();
            manager->deleteLater();
        });

//    QString style="background-image:url("+imagePath+");";
//    ui->recMusicImage->setStyleSheet(style);
}

bool RecBoxItem::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->musicImageBox){
        if(QEvent::Enter==event->type()){

            qDebug()<<"鼠标进入";

            //添加上移动画
            QPropertyAnimation *animal=new QPropertyAnimation(ui->musicImageBox,"geometry");
            animal->setDuration(150);
            animal->setStartValue(QRect(9,9,ui->musicImageBox->width(),ui->musicImageBox->height()));
            animal->setEndValue(QRect(9,0,ui->musicImageBox->width(),ui->musicImageBox->height()));
            animal->start();

            connect(animal,&QPropertyAnimation::finished,this,[=](){
                delete animal;
            });
        }
        else if(QEvent::Leave==event->type()){
            qDebug()<<"鼠标离开";
            QPropertyAnimation *animal=new QPropertyAnimation(ui->musicImageBox,"geometry");
            animal->setDuration(150);
            animal->setStartValue(QRect(9,0,ui->musicImageBox->width(),ui->musicImageBox->height()));
            animal->setEndValue(QRect(9,9,ui->musicImageBox->width(),ui->musicImageBox->height()));
            animal->start();

            connect(animal,&QPropertyAnimation::finished,this,[=](){
                delete animal;
            });
        }
        return true;
    }
    return QObject::eventFilter(watched,event);
}

QString RecBoxItem::cacheFilePath(const QString &url)
{
    QByteArray hash=QCryptographicHash::hash(url.toUtf8(),QCryptographicHash::Md5);

    QString filename=QString(hash.toHex())+".jpg";

    QString cacheDir=QStandardPaths::writableLocation(QStandardPaths::CacheLocation);

    QDir().mkpath(cacheDir);

    return QDir(cacheDir).filePath(filename);
}

void RecBoxItem::on_recMusicBtn_clicked()
{
    QString listName=ui->recBoxItem->text();
    qDebug()<<"点击了，并获得listName"<<listName;
    QUrl url(QString("http://127.0.0.1:8080/musicList/%1").arg(listName));


    QNetworkRequest request(url);

    QNetworkReply *reply = manager->get(request);

     connect(reply, &QNetworkReply::finished, this, [=]() {
            onMusicListReply(reply, listName);
        });

}



void RecBoxItem::onMusicListReply(QNetworkReply *reply, const QString &listName)
{



    if(reply->error()!=QNetworkReply::NoError){
        qDebug()<<"请求歌单:"<<listName<<"错误";
        reply->deleteLater();

        return;
    }


    QByteArray responseData=reply->readAll();

    reply->deleteLater();

    QJsonParseError jsonError;
    QJsonDocument jsonDoc=QJsonDocument::fromJson(responseData,&jsonError);
    if (jsonError.error != QJsonParseError::NoError || !jsonDoc.isArray()) {
            qDebug() << "JSON 解析失败或不是数组";
            return;}

    QJsonArray arr=jsonDoc.array();



    for(auto v:arr){
        if(!v.isObject())continue;

        QJsonObject obj=v.toObject();

        QString title = obj.value("title").toString();
        QString artist = obj.value("artist").toString();
        QString album = obj.value("album").toString();
        qint64 duration = obj.value("duration").toInt();

        QString songName = QString("%1 - %2.mp3").arg(artist, title);
        QUrl songUrl(QString("http://127.0.0.1:8080/musicFile/%1/%2")
                                .arg(listName, songName));


        Music m;
        m.setMusicId(QUuid::createUuid().toString());
        m.setMusicName(title);
        m.setMusicSinger(artist);
        m.setMusicAlbumn(album.isEmpty() ? "未知专辑" : album);
        m.setMusicDuration(duration);
        m.setMusicUrl(songUrl);
        m.setMusicNet();  // 标记来自网络

        netList.push_back(m);
    }


    emit netMusicListready(netList,listName);
}
